package com.matou.commons.interceptor;

import com.matou.commons.constants.BaseConst;
import com.matou.commons.constants.Resp;
import com.matou.commons.exception.MtError;
import com.matou.commons.util.BaseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author CM
 * @Date 2021/5/9 15:10
 * @Description CmServerProtectInterceptor  校验Zuul Token 的拦截器
 * @Version 1.0
 */
public class MaTouServerProtectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头中获取 Zuul Token
        String token = request.getHeader(BaseConst.ZUUL_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(BaseConst.ZUUL_TOKEN_VALUE.getBytes()));
        // 校验 Zuul Token的正确性
        if (StringUtils.equals(zuulToken, token)) {
            return true;
        } else {
            // 请通过网关获取资源
            BaseUtil.makeResponse(response,MediaType.APPLICATION_JSON_UTF8_VALUE,HttpServletResponse.SC_FORBIDDEN, Resp.failure(MtError.MT_000001));
            return false;
        }
    }
}
